﻿using Infra_Common.redis;
using MediatR;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using xiaodingmarket_Domain.CommandHandlers;
using xiaodingmarket_Domain.Commands;
using xiaodingmarket_Domain.Events.Commodity;
using static xiaodingmarket_Domain.Models.EunmType;

namespace xiaodingmarket_service
{
    public class AutoRedisService : IHostedService
    {
        private readonly IServiceProvider _serviceProvider;
        public AutoRedisService(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            using (var scope = _serviceProvider.CreateScope())
            {
                //异步处理自动审核任务
                var redis = scope.ServiceProvider.GetRequiredService<RedisClient>();
                var command = scope.ServiceProvider.GetRequiredService<IRequestHandler<ReviewCommodityCommand, bool>>();
                await redis.Sub("__keyevent@0__:expired",(Redisvalue)=>
                {
                    var t = JsonConvert.DeserializeObject<CommodityCreateEvent>(Redisvalue);
                    ReviewCommodityCommand c = new ReviewCommodityCommand(t.commodityid, Commoditystate.reviewok, new Guid("System"));

                    var cts = new CancellationTokenSource();
                    command.Handle(c, cts.Token);
                    return true;
                });


            }
        }
        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }
}
